﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint.Administration;
using System.IO;
using Microsoft.SharePoint.Utilities;

namespace CodePlex.RoundedButton.Code.JobDefinitions
{
	public class BrowserJobDefinition : SPJobDefinition
	{
		#region Constructors
		public BrowserJobDefinition() : base() { }

		public BrowserJobDefinition(string name, SPWebApplication webApp) : base(name, webApp, null, SPJobLockType.None) { }
		#endregion

		#region Variables
		public override string DisplayName
		{
			get { return "Add custom browser defintion file"; }
		}

		public override string Description
		{
			get { return "Copies a custom browser definition file to the App_Browser directory"; }
		}
		#endregion

		public override void Execute(Guid targetInstanceId)
		{
			bool add = (bool)this.Properties["add"];

			foreach (SPUrlZone zone in Enum.GetValues(typeof(SPUrlZone)))
			{
				if (this.WebApplication.IisSettings.Keys.Contains(zone))
				{
					string path = this.WebApplication.IisSettings[zone].Path + @"\App_Browsers\adapters.browser";

					if (add)
					{
						// when active feature
						if (!File.Exists(path))
						{
							// get source
							string sourcePath = SPUtility.GetGenericSetupPath(@"TEMPLATE\FEATURES\CodePlex.RoundedButton_BrowserDefinitionTimerJob\Browser\adapters.browser");
							if (File.Exists(sourcePath))
							{
								// copy our browser file to inetpub\{app}\app_browsers\
								File.Copy(sourcePath, path);

								// update lastwritetime on compat.browser (so sharepoint will load our custom file)
								string compatPath = this.WebApplication.IisSettings[zone].Path + @"\App_Browsers\compat.browser";
								File.SetLastWriteTime(compatPath, DateTime.Now);
							}
						}
					}
					else
					{
						// When deactive feature
						if (File.Exists(path))
						{
							File.Delete(path);
						}
					}
				}
			}
		}
	}
}